package org.glorylight.hacks.social.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.RandomStringUtils;
import org.glorylight.hacks.social.data.MailMe;
import org.glorylight.hacks.social.data.UserData;
import org.glorylight.hacks.social.data.UserNetworkData;
import org.glorylight.hacks.social.service.MailService;
import org.glorylight.hacks.social.service.UserNetworkService;
import org.glorylight.hacks.social.service.UserService;
import org.glorylight.hacks.social.util.ModelHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.sun.jersey.api.representation.Form;

@Component
@Scope("prototype")
@Path("/userinfo")
public class UserController extends AbstractBaseController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MailService mailService;
	
	@Autowired
	private UserNetworkService userNetworkService;
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Path("/userinfo")
	public UserData getUserInformation() {
		UserData uData = userService.find(getActiveLogin());
		if (uData != null) {
			uData.setPassword(null);
			return uData;
		}
		
		return new UserData();
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Path("/updateuserinfo")
	public Response updateUserInfo(Form formData) {
		String birthDate = formData.getFirst("birthDate");
		String gender = formData.getFirst("gender");
		String mobileNo = formData.getFirst("mobileNo");
		String babyName = formData.getFirst("babyName");
		String babyBirthDate = formData.getFirst("babyBirthDate");
		
		UserData userData = userService.find(getActiveLogin());
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
		userData.setGender(gender);
		userData.setMobileNo(mobileNo);
		userData.setBabyName(babyName);
		try {
			userData.setBirthDate(formatter.parse(birthDate));
			userData.setBabyBirthDate(formatter.parse(babyBirthDate));
			
			userService.updateUser(userData);
		} catch (Exception e) {
			log.error("Failed to update user information", e);
			return Response.status(Response.Status.CONFLICT).build();
		}
		
		return Response.status(Response.Status.OK).build();
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Path("/changepassword")
	public Response changePassword(Form formData) {
		try {
			String password = formData.getFirst("newpassword");
			UserData userData = userService.find(getActiveLogin());
			userData.setPassword(password);
			userService.updateUser(userData);
		} catch (Exception e) {
			log.error("Failed to update user information", e);
			return Response.status(Response.Status.CONFLICT).build();
		}
		
		return Response.status(Response.Status.OK).build();
	}
	
	@GET
	@Consumes(MediaType.APPLICATION_JSON)
	@Path("/forget")
	public Response forgetPassword(Form formData) {
		try {
			String email = formData.getFirst("email");
			String generatedPassword = RandomStringUtils.random(10, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*()<>{}-+=?");
			UserData uData =userService.find(email);
			uData.setPassword(generatedPassword);
			userService.updateUser(uData);
			MailMe mail = new MailMe("Babytivities account has been reset", 
					"noreply@babytivities.com", 
					new String[] {email}, 
					"resetPassword", 
					new String[]{uData.getFirstName() + " " + uData.getLastName(), email, generatedPassword});
			mailService.sendMail(mail);
		} catch (Exception e) {
			log.error("Failed to reset password", e);
			return Response.status(Response.Status.CONFLICT).build();
		}
		
		return Response.status(Response.Status.OK).build();
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Path("/follow/{friendId}")
	public Response followUser(@PathParam("friendId") String friendId) {
		try {
			UserData userData = userService.find(getActiveLogin());
			UserNetworkData data = new UserNetworkData(UUID.randomUUID(), ModelHelper.convertUserData(userData), friendId, new Date());
			userNetworkService.addNetwork(data);
			
			return Response.status(Response.Status.OK)
					.entity("user followed.")
					.type(MediaType.TEXT_PLAIN).build();
			
		} catch (Exception e) {
			log.error("error ocur when connecting user ..", e);
		}
		return Response.status(Response.Status.BAD_REQUEST)
				.type(MediaType.TEXT_PLAIN).build();
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Path("/unfollow/{friendId}")
	public Response unFollowUser(@PathParam("friendId") String friendId) {
		try {
			userNetworkService.deleteConnection(getActiveLogin(), friendId);
			
			return Response.status(Response.Status.OK)
					.entity("user unfollowed.")
					.type(MediaType.TEXT_PLAIN).build();
		} catch (Exception e) {
			log.error("error ocur when connecting user ..", e);
		}
		return Response.status(Response.Status.BAD_REQUEST)
				.type(MediaType.TEXT_PLAIN).build();
	}
}
